package com.example.wearing.wardrobe;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wearing.R;
import com.example.wearing.find.AddPostActivity;
import com.example.wearing.tools.BitmapBinder;
import com.example.wearing.tools.ImageUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddClothesActivity extends AppCompatActivity {

    private static final String TAG = "AddClothesActivity";

    public static final int RESQUEST_CODE_CHOOSE = 2;
    private String imageBase64, clothesType, clothesName, clothesColor, username;
    private Bitmap imgBitmap;
    private String imageUrl = "";
    Map<String, String[]> nameMap;  //名称列表
    final String[] types = {"无分类", "上装", "下装", "内衣", "鞋子", "包包", "配饰"}; //种类列表
    final String[] colors = {"黑色系", "白色系", "灰色系", "裸色系", "蓝色系", "绿色系", "黄色系", "紫色系", "橙色系", "粉色系", "红色系", "棕色系"}; //颜色列表
    int[] imageId=new int[]{R.drawable.black, R.drawable.white, R.drawable.grey, R.drawable.khaki,
            R.drawable.blue, R.drawable.green, R.drawable.yellow, R.drawable.purple, R.drawable.orange,
            R.drawable.pink, R.drawable.red, R.drawable.brown};

    private Handler handler;
    private Intent intent;
    private int intentFlag, clothesId, userId;
    private String jdbcUrl, jdbcUser, jdbcPassword;
    private ImageView addImgBtn;
    private TextView clothesTypeText, clothesNameText, clothesColorText;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_clothes);

        init();
        //返回
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        
        //获取intent值
        intent = getIntent();
        intentFlag = intent.getIntExtra("c_flag", 0);
        if(intentFlag == 1){
            //说明为add
            Log.i(TAG, "onCreate: intent--add");
        }else if(intentFlag == 2){
            //说明为修改
            Log.i(TAG, "onCreate: intent--alter");
            clothesType = intent.getStringExtra("c_type");
            clothesName = intent.getStringExtra("c_name");
            clothesColor = intent.getStringExtra("c_color");
            clothesId = intent.getIntExtra("c_id", 0);
            //使用bundle接收
            Bundle bundle = intent.getExtras();
            BitmapBinder bitmapBinder = (BitmapBinder) bundle.getBinder("c_img");
            imgBitmap = bitmapBinder.getBitmap();
            imageBase64= ImageUtil.imageToBase64(imgBitmap);

            //将其放到控件中
            clothesTypeText.setText(clothesType);
            clothesNameText.setText(clothesName);
            clothesColorText.setText(clothesColor);
            addImgBtn.setImageBitmap(imgBitmap);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        super.onOptionsItemSelected(item);
        return true;
    }

    //初始化
    private void init(){
        addImgBtn = findViewById(R.id.addImgBtn);
        clothesTypeText = findViewById(R.id.typeContent);
        clothesNameText = findViewById(R.id.nameContent);
        clothesColorText = findViewById(R.id.colorContent);

        clothesType = clothesTypeText.getText().toString().trim();
        clothesColor = clothesColorText.getText().toString().trim();
        clothesName = clothesNameText.getText().toString().trim();

        //从SharedPreferences中获取用户名
        SharedPreferences sp = this.getSharedPreferences("user", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        username = sp.getString("user_name","");
        userId = sp.getInt("user_id",0);
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");

        //衣物名称——细分类别初始化
        nameMap = new HashMap<String, String[]>();
        String[] name1 = {"无"};
        String[] name2 = {"短袖", "长袖", "卫衣", "衬衫", "毛衣", "外套", "大衣", "棉服", "羽绒服"};
        String[] name3 = {"牛仔裤", "运动裤", "打底裤", "裙子", "短裤", "西装裤"};
        String[] name4 = {"无"};
        String[] name5 = {"皮鞋", "运动鞋", "帆布鞋", "高跟鞋", "靴子", "棉鞋"};
        String[] name6 = {"钱包", "斜挎包", "手提包", "背包", "箱包"};
        String[] name7 = {"帽子", "围巾", "项链", "墨镜", "手表", "耳饰"};
        nameMap.put("无分类", name1);
        nameMap.put("上装", name2);
        nameMap.put("下装", name3);
        nameMap.put("内衣", name4);
        nameMap.put("鞋子", name5);
        nameMap.put("包包", name6);
        nameMap.put("配饰", name7);
    }

    //点击添加照片，弹出相册
    public void chooseImage(View view){

        Log.i(TAG, "onClick: 相册");
        //从相册选取照片
        if(ContextCompat.checkSelfPermission(AddClothesActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
            //真正去打开相册
            openAlbum();
        }else{
            //去申请权限
            ActivityCompat.requestPermissions(AddClothesActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }

    }

    //权限管理
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 0) {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                openAlbum();
            }else{
                Toast.makeText(this, "您没有获得访问相册权限~", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @SuppressLint("Range")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == RESQUEST_CODE_CHOOSE){
            //从相册选取照片
            Uri uri = data.getData();
            String path = null;
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if(cursor != null) {
                if(cursor.moveToFirst()) {
                    path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
                cursor.close();
            }
            if(path != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                imageUrl = path;
                Log.i(TAG, "onActivityResult: path:"+path);///storage/emulated/0/DCIM/Camera/IMG_20220301_180527.jpg

                addImgBtn.setImageBitmap(bitmap);
                imageBase64= ImageUtil.imageToBase64(bitmap);
            }
        }
    }

    private void openAlbum(){
        Intent intent = new Intent("android.intent.action.PICK");
        intent.setType("image/*");
        startActivityForResult(intent, RESQUEST_CODE_CHOOSE);
    }

    //选择种类——弹出选择框
    public void selectType(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.clothes);
        builder.setTitle("选择衣物种类");
        //    设置一个下拉的列表选择项
        builder.setItems(types, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Log.i(TAG, "onClick: 选择的类别为：" + types[which]);
                clothesType = types[which];
                clothesTypeText.setText(clothesType);
            }
        });
        builder.show();
    }

    //选择详细种类——名称——需要和种类联动
    public void selectName(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.clothes);
        builder.setTitle("选择衣物名称");
        //    指定下拉列表的显示数据，根据类别选择
        String[] clothesList = nameMap.get(clothesType);
        //    设置一个下拉的列表选择项
        builder.setItems(clothesList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Log.i(TAG, "onClick: 选择的名称为：" + clothesList[which]);
                clothesName = clothesList[which];
                clothesNameText.setText(clothesName);
            }
        });
        builder.show();
    }

    //选择颜色
    public void selectColor(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.color);
        builder.setTitle("选择衣物颜色");

        List<Map<String,Object>> listItems=new ArrayList<Map<String,Object>>();
        //通过for循环将图片id和列表项文字放到map中，并添加到List集合中
        for (int i = 0; i < imageId.length; i++) {
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("image", imageId[i]);
            map.put("title", colors[i]);
            listItems.add(map);
        }
        final SimpleAdapter adapter=new SimpleAdapter(this,listItems,
                R.layout.color_item,new String[]{"title","image"},new int[]{R.id.title,R.id.image});

        //    设置一个下拉的列表选择项
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Log.i(TAG, "onClick: 选择的颜色为：" + colors[which]);
                clothesColor = colors[which];
                clothesColorText.setText(clothesColor);
            }
        });
        builder.show();
    }

    //保存
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    public void saveClothesBtn(View view) {

        //设置种类、名称、颜色、图片不为空
        if(clothesType.isEmpty()){
            Toast.makeText(getApplicationContext(), "请选择衣物种类", Toast.LENGTH_SHORT).show();
            return;
        }else if(clothesName.isEmpty()){
            Toast.makeText(getApplicationContext(), "请选择衣物名称", Toast.LENGTH_SHORT).show();
            return;
        }else if(clothesColor.isEmpty()){
            Toast.makeText(getApplicationContext(), "请选择衣物颜色", Toast.LENGTH_SHORT).show();
            return;
        }else if(imageBase64.isEmpty()){
            Toast.makeText(getApplicationContext(), "请选择图片", Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(getApplicationContext(), "正在提交，请稍等~", Toast.LENGTH_SHORT).show();

        //上传数据到表中
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg){
                Log.i(TAG, "handleMessage: 收到消息");
                if(msg.what == 1){
                    //接收消息__add
                    int res = (int) msg.obj;
                    if(res == 1){
                        //发布成功
                        Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
                        //返回衣橱界面
                        setResult(20, intent);
                        finish();
                    }else if(res == 2){
                        //发布失败
                        Toast.makeText(getApplicationContext(), "添加失败", Toast.LENGTH_SHORT).show();
                    }
                }else if(msg.what == 2){
                    //接收消息————alter
                    int res = (int) msg.obj;
                    if(res == 1){
                        //修改成功
                        Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                        //返回衣橱界面
                        setResult(40, intent);
                        finish();
                    }else if(res == 2){
                        //发布失败
                        Toast.makeText(getApplicationContext(), "修改失败", Toast.LENGTH_SHORT).show();
                    }
                }
                super.handleMessage(msg);
            }
        };


        if(intentFlag == 1){
            Thread thread = new Thread(addClothesRun);
            thread.start();
        }else if(intentFlag == 2){
            Thread thread2 = new Thread(alterClothesRun);
            thread2.start();
        }

    }

    //添加衣物，insert数据库
    private Runnable addClothesRun = new Runnable() {
        @Override
        public void run() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
                Statement st = (Statement) cn.createStatement();
                int insertCode;
                try {
                    String insertSql = "INSERT INTO clothes (c_type, c_name, c_color, c_img, c_uid) VALUES ('" + clothesType + "','" + clothesName + "','" + clothesColor + "','" + imageBase64 + "'," + userId + ")";
                    int result = st.executeUpdate(insertSql);// 返回值代表收到影响的行数
                    Log.i(TAG, "run: 插入数据成功" + result + "行----" + username);
                    insertCode = 1;

                } catch (SQLException e) {
                    insertCode = 2;
                    Log.i(TAG, "run:SQL fail!!!__" + e);
                    e.printStackTrace();
                }

                //发送消息
                Message msg = handler.obtainMessage(1, insertCode);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---插入结果");

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
        }
    };

    //修改衣物，update数据库
    private Runnable alterClothesRun = new Runnable() {
        @Override
        public void run() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser ,jdbcPassword);
                Statement st = (Statement) cn.createStatement();
                int updateCode;
                try {
                    String updateSql = "UPDATE clothes set c_type = '" + clothesType+ "',c_name='"+ clothesName
                            + "',c_color='" + clothesColor +"',c_img='" + imageBase64
                            + "' where c_id=" + clothesId;
                    int result = st.executeUpdate(updateSql);// 返回值代表收到影响的行数
                    Log.i(TAG, "run: 修改数据成功" + result + "行----" + username);
                    updateCode = 1;

                } catch (SQLException e) {
                    updateCode = 2;
                    Log.i(TAG, "run:SQL fail!!!__" + e);
                    e.printStackTrace();
                }

                //发送消息
                Message msg = handler.obtainMessage(2, updateCode);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---修改结果");

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
        }
    };

}